package com.xzcs.service.blog.search;

import com.xzcs.service.BaseService;
import com.xzcs.util.Constants;
import com.xzcs.util.lucene.LuceneUtils;
import com.xzcs.util.web.RequestUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SearchService extends BaseService {

	public List<Map<String, Object>> searchContents(HttpServletRequest request){
		String fileRoot = propertyUtils.getPropertyValue(Constants.DEFAULT_FILE_UPLOAD_PATH);
		String indexDir = fileRoot + "lucene";
		String keyword = RequestUtils.getValue(request, "keyword");
		Map<String, String> param = new HashMap<String, String>();
		param.put("title", keyword);
		param.put("description", keyword);
		param.put("key_words", keyword);
		//param.put("content", keyword);
		Query query = LuceneUtils.createQuery(param);
		
		TopDocs topDocs = LuceneUtils.searchDocs(query, 50, indexDir);
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		logger.debug("查询结果："+scoreDocs.length);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (ScoreDoc scoreDoc : scoreDocs) {
			Map<String, Object> map = new HashMap<String, Object>();
			Document d = LuceneUtils.searchDoc(scoreDoc.doc, indexDir);
			String title = getInfo(d, "title");
			map.put("content_id", getInfo(d, "content_id"));
			map.put("title", title);
			map.put("description", getInfo(d, "description"));
			map.put("content", getInfo(d, "content"));
			map.put("title_img", getInfo(d, "title_img"));
			map.put("category_id", getInfo(d, "category_id"));
			map.put("category_name", getInfo(d, "category_name"));
			map.put("author", getInfo(d, "author"));
			map.put("create_time", getInfo(d, "create_time"));
			map.put("views_cnt", getInfo(d, "views_cnt"));
			map.put("key_words", getInfo(d, "key_words"));
			
			list.add(map);
		}
		return list;
	}
	
	public String getInfo(Document d, String key){
		IndexableField field = d.getField(key);
		if (null != field) {
			return field.stringValue();
		}
		return "";
	}
	
}
